﻿using AG.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharePointOptimizer.Model;
using SharePointOptimizer.BL.DataAnalysis;

namespace SharePointOptimizer.BL.DataAnalysis.IssueTypes
{
    public class SiteTooManyLibrariesCheck : IssueTypeCheckBase
    {

        public SiteTooManyLibrariesCheck(int issueTypeId)
            : base(issueTypeId)
        {

        }

        public override void Check()
        {

            try
            {
                // Get all Service instance that has ServiceTypeID 1
                Farm farm = dc.Farms.FirstOrDefault();


                if (farm != null)
                {

                    Service service = farm.Services.SingleOrDefault(s => s.TypeName == "Microsoft SharePoint Foundation Web Application");


                    if (service != null)
                    {

                        var QrySites = from s in dc.Webs
                                       where s.Lists.Count() > issueType.ThresholdValue
                                       select new { s.WebID, url = s.ServerRelativeUrl, nrLists = s.Lists.Count() };
                        foreach (var site in QrySites)
                        {
                            Issue issue = new Issue();
                            issue.IssueType = issueType;
                            issue.TargetId = site.WebID;
                            issue.Description = issueType.Description.Replace("{siteURL}", site.url);
                            issue.Description = issue.Description.Replace("{nrLibraries}", site.nrLists.ToString());
                            issue.Description = issue.Description.Replace("{maxNrLibraries}", issueType.ThresholdValue.ToString());
                            dc.Issues.InsertOnSubmit(issue);

                        }
                        dc.SubmitChanges();
                    }


                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

    }

}
